#!/usr/bin/env python3
# _*_ coding:UTF-8 _*_
"""
__author__ = 'wangshaowei'
"""

import argparse
import os
import plistlib
import re
import subprocess
import stat
import shutil

mp_home_dir = os.path.expanduser("~/Library/MobileDevice/Provisioning Profiles")
mp_ext_name = ".mobileprovision"


def mp_path_in_dir(dir_path):
    """
    查找dir_path目录下所有的mobileprovision文件
    :param dir_path: 目录路径
    :return: mobileprovision文件路径列表
    """
    global mp_ext_name
    path_list = []
    global mp_ext_name
    for file_name in os.listdir(dir_path):
        if file_name.endswith(mp_ext_name):
            file_path = os.path.join(dir_path, file_name)
            path_list.append(file_path)
    return path_list


def plist_from_mp(file_path):
    """
    从mobileprovision文件里提取出plist对象
    :param file_path: mobileprovision文件路径
    :return: plist对象
    """
    with open(file_path, "rb") as fp:
        file_content = fp.read()

    p_start = re.escape("<?xml")
    p_end = re.escape("</plist>")
    pattern_str = "{}.+{}".format(p_start, p_end)
    result = re.search(pattern_str, file_content, flags=re.DOTALL)
    xml_content = result.group()
    return plistlib.readPlistFromString(xml_content)


def add_mobileprovision(mp_file_path):
    """
    导入新的mobileprovision文件
    :param mp_file_path: mobileprovision文件路径
    :return:
    """
    global mp_home_dir
    current_mp = plist_from_mp(mp_file_path)
    current_name = current_mp["Name"]
    current_uuid = current_mp["UUID"]
    print("开始导入mobileprovision 文件：")

    # 删除同name的mp文件
    global mp_home_dir
    has_same_name = False  # 是否有同Name的文件
    for file_path in mp_path_in_dir(mp_home_dir):
        tmp_mp = plist_from_mp(file_path)
        tmp_name = tmp_mp["Name"]
        if current_name == tmp_name:
            has_same_name = True
            os.remove(file_path)
            print("\t- 删除'Name'相同的文件: {}".format(file_path))
    if not has_same_name:
        print("\t* 没有同Name({})的mobileprovision文件".format(current_name))

    # 导入新的 mobileprovision 文件
    file_name = "{}{}".format(current_uuid, mp_ext_name)
    dst_path = os.path.join(mp_home_dir, file_name)
    shutil.copy(mp_file_path, dst_path)
    # 修改文件权限"-rw-r--r-- "
    os.chmod(dst_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    print("+ 成功导入mobileprovision: \n\tfrom: {}\n\tto: {}".format(mp_file_path, dst_path))


def delete_mp(file_path):
    """
    删除mobileprovision文件，或者file_path目录下的mobileprovision文件
    :param file_path: mobileprovision文件路径或者目录
    :return:
    """
    if os.path.isfile(file_path):
        os.remove(file_path)
        print("\t- 删除源文件: {}".formatfile_path)
    elif os.path.isdir(file_path):
        for tmp_path in mp_path_in_dir(file_path):
            os.remove(tmp_path)
            print("\t- 删除文件: {}".format(tmp_path))


def parse_arg():
    """解析命令行的输入的参数"""
    parser = argparse.ArgumentParser("检测、导入 mobileprovision 文件")
    parser.add_argument("--path", help="(可选)mobileprovision路径，或者目录路径，为空则为桌面路径")
    parser.add_argument("-D", "--delete-origin", action="store_true",
                        help="删除原始的 mobileprovision 文件")

    return parser.parse_args()


def main():
    """主入口"""
    global mp_ext_name
    command_params = parse_arg()
    is_delete_origin = command_params.delete_origin
    mp_path = command_params.path

    if not mp_path:
        mp_path = os.path.expanduser("~/Desktop")  # 桌面路径
        print("使用默认路径：{}".format(mp_path))
    mp_path = os.path.expanduser(mp_path)

    if os.path.isfile(mp_path) and mp_path.endswith(mp_ext_name):
        add_mobileprovision(mp_path)
    elif os.path.isdir(mp_path):
        for file_name in os.listdir(mp_path):
            if not file_name.endswith(mp_ext_name):
                continue
            file_path = os.path.join(mp_path, file_name)
            add_mobileprovision(file_path)
    else:
        raise Exception("not support: {}".format(mp_path))

    # 删除原始 mobileprovision 文件
    if is_delete_origin:
        print("\n* 删除原始文件：")
        delete_mp(mp_path)


if __name__ == '__main__':
    main()
